<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BillingInfoController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $tenantId = $request->user()?->tenant_id ?? $request->attributes->get('tenant_id');

        $tenant = $tenantId ? Tenant::find($tenantId) : null;

        if (! $tenant) {
            return response()->json([
                'code' => 404,
                'message' => '租户不存在或已被删除',
                'data' => null,
            ], 404);
        }

        return response()->json([
            'code' => 0,
            'message' => '获取开票信息成功',
            'data' => $this->transformTenant($tenant),
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $tenantId = $request->user()?->tenant_id ?? $request->attributes->get('tenant_id');

        $tenant = $tenantId ? Tenant::find($tenantId) : null;

        if (! $tenant) {
            return response()->json([
                'code' => 404,
                'message' => '租户不存在或已被删除',
                'data' => null,
            ], 404);
        }

        $validated = $request->validate([
            'invoice_contact_phone' => 'nullable|string|max:50',
            'invoice_mailing_address' => 'nullable|string|max:500',
            'invoice_recipient' => 'nullable|string|max:100',
        ]);

        $tenant->fill($validated);
        $tenant->save();

        return response()->json([
            'code' => 0,
            'message' => '开票联系信息更新成功',
            'data' => $this->transformTenant($tenant->fresh()),
        ]);
    }

    /**
     * @return array<string, mixed>
     */
    private function transformTenant(Tenant $tenant): array
    {
        $invoiceable = $tenant->invoiceable_amount ?? 0;

        return [
            'company_name' => $tenant->company_name,
            'tax_registration_number' => $tenant->tax_registration_number,
            'address' => $tenant->address,
            'bank_name' => $tenant->bank_name,
            'bank_account' => $tenant->bank_account,
            'invoice_contact_phone' => $tenant->invoice_contact_phone,
            'invoice_mailing_address' => $tenant->invoice_mailing_address,
            'invoice_recipient' => $tenant->invoice_recipient,
            'invoiceable_amount' => (float) $invoiceable,
            'formatted_invoiceable_amount' => number_format((float) $invoiceable, 2, '.', ''),
        ];
    }
}
